package org.flexthinker.binding.bean
{
    import org.flexthinker.binding.bean.support.PropertyReader;
    import org.flexthinker.binding.bean.support.PropertyResolutionError;
    import org.flexthinker.binding.bean.support.PropertyWriter;
    import org.flexthinker.binding.form.FormModel;

    /**
     * @author Dragos Dascalita Haut
     */
    public class BeanProperty extends PropertyHelper
    {
        public function BeanProperty(source:Object, path:String)
        {
            super(source,path);
        }

        public static function create (path:String ):BeanProperty
        {
            return new BeanProperty(null, path );
        }


        override public function getValue():Object
        {
            return PropertyReader.getValue(getSource(), getPath() );
        }


        override public function setValue( value:Object ):void
        {
            PropertyWriter.setValue(getSource(), getPath(), value);
        }


        override public function setSource( source:Object ):void
        {
            super.setSource( source );

            try
            {
                watchChangesInPath();
            }
            catch( err:Error)
            {
                throw new PropertyResolutionError(err);
            }

            /* MOVE THIS INTO FormModelProperty
            if ( source is FormModel )
            {
                if ( getPath() && getPath().indexOf(".") >= 0 )
                {
                    throw new Error("Nested properties not allowed with FormModel instances");
                }
                watchChangesInFormModelProperty();
            }
            */
        }

        // --------------------
        //   internal methods
        // ---------------------
        private function watchChangesInPath():void
        {
            resetWatchers();

            var subpaths:Array = getPath().split(".");
            var subpathHost:Object = getSource();
            for each ( var subpath:String in subpaths )
            {
                subpathHost = subpathHost[subpath];
                if ( subpath != null && subpath.length > 0 )
                {
                    listenTo( createValueModel(subpathHost, subpath) );
                }
            }
        }

        /*
        private function watchChangesInFormModelProperty():void
        {
            resetWatchers();

            listenTo( FormModel(getSource()).getValueModel( getPath() ) );
        }
        */
    }
}